package tron.service;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;

public class FtpOne {
    public static void main(String[] args) throws FileNotFoundException {
        FTPClient ftpClient = loginFTP("192.168.101.3", 2121, "tron", "123456");
        String fileName = "PrimerPlus6.pdf";
        File file = ResourceUtils.getFile("classpath:"+fileName);
        uploadFileToFTP(ftpClient,file.getAbsolutePath(),"tron",fileName);
    }


    public static FTPClient loginFTP(String host, int port, String userName, String password) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            // 连接FTP服务器
            ftpClient.connect(host, port);
            // 登陆FTP服务器
            ftpClient.login(userName, password);
            // 中文支持
            ftpClient.setControlEncoding("UTF-8");
            // 设置文件类型为二进制（如果从FTP下载或上传的文件是压缩文件的时候，不进行该设置可能会导致获取的压缩文件解压失败）
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.out.println("连接FTP失败，用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                System.out.println("FTP连接成功!");
            }
        } catch (Exception e) {
            System.out.println("登陆FTP失败，请检查FTP相关配置信息是否正确！"+e.getMessage());
        }
        return ftpClient;
    }


    /**
     * 上传本地文件到FTP
     * @param ftpClient         已经登陆成功的FTPClient
     * @param localFilePath     要上传的本地文件路径
     * @param ftpFilePath       要保存的FTP文件路径
     */
    public static void uploadFileToFTP(FTPClient ftpClient, String localFilePath, String ftpFilePath,String fileName) {
        FileInputStream fis = null;
        try {
            //判断FPT目标文件夹时候存在不存在则创建
            if(!ftpClient.changeWorkingDirectory(ftpFilePath)){
                ftpClient.makeDirectory(ftpFilePath);
            }
            ftpClient.enterLocalPassiveMode();
            ftpClient.setBufferSize(1024*1024);
            //跳转目标目录
            ftpClient.changeWorkingDirectory(ftpFilePath);
            // 文件保存
            fis = new FileInputStream(new File(localFilePath));
            Instant now = Instant.now();
            boolean storeFile = ftpClient.storeFile(fileName, fis);
            Instant end = Instant.now();
            if (storeFile) {
                System.out.println("FTP文件上传成功！"+"耗时："+ Duration.between(now,end).toMillis());
            }
        } catch (Exception e) {
            System.out.println("FTP文件上传失败！"+e.getMessage());
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
